/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.improvement.controller;

import com.koron.common.Excel;
import com.koron.common.StaffAttribute;
import com.koron.common.bean.StaffBean;
import com.koron.common.permission.SPIAccountAnno;
import com.koron.common.web.Util;
import com.koron.improvement.bean.Assessment;
import com.koron.improvement.service.api.AssessmentService;
import com.koron.improvement.utils.BusinessCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;
import springfox.documentation.annotations.ApiIgnore;

import java.io.File;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "Assessment", description = "评估考核")
@RestController
@RequestMapping(value = "/assessment")
public class AssessmentController {

    @Autowired
    private AssessmentService assessmentService;

    @Autowired
    private Util util;

    private final Logger logger = LoggerFactory.getLogger(AssessmentController.class);

    @ApiOperation("评估考核列表")
    @RequestMapping(value = "/list.htm", method = {RequestMethod.GET})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "assessmentYear", value = "年份", dataType = "Integer"),
            @ApiImplicitParam(name = "assessmentTimeType", value = "考核时间类型0年,1季度,2月份", dataType = "Integer"),
            @ApiImplicitParam(name = "assessmentTimeValue", value = "考核时间值", dataType = "Integer"),
            @ApiImplicitParam(name = "corpCode", value = "公司Code", dataType = "String"),
            @ApiImplicitParam(name = "corpName", value = "公司名称", dataType = "String"),
            @ApiImplicitParam(name = "deptName", value = "部门名称", dataType = "String"),
            @ApiImplicitParam(name = "assessmentType", value = "评估考核类型：0.标准化自评，1.年度评价，2.日常考核", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "assessmentGrade", value = "评估考核级别：0.集团对公司，1.公司对场站", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "page", value = "当前页", dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", dataType = "Integer")
    })
    public MessageBean<?> list(@RequestParam(defaultValue = "0") Integer assessmentGrade, String deptName,
                               Integer assessmentYear, Integer assessmentTimeType, Integer assessmentTimeValue, String corpName
            , Integer assessmentType, Integer page, Integer pageSize, String corpCode) {
        return assessmentService.queryList(assessmentGrade, deptName, assessmentYear, assessmentTimeType, assessmentTimeValue,
                corpName, assessmentType, page, pageSize, corpCode);
    }

    @ApiOperation("评估考核详情")
    @RequestMapping(value = "/detail.htm", method = {RequestMethod.GET})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "assessmentId", value = "考核id", dataType = "Integer"),
    })
    public MessageBean<?> detail(String assessmentId) {
        return assessmentService.detail(assessmentId);
    }

    @ApiOperation("评估考核添加")
    @RequestMapping(value = "/saveOrCommit.htm", method = {RequestMethod.POST})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "approverCodeListStr", value = "审批人集合", dataType = "String"),
            @ApiImplicitParam(name = "assessmentStr", value = "审核对象字符串", dataType = "String"),
            @ApiImplicitParam(name = "files", value = "文件", dataType = "file"),
            @ApiImplicitParam(name = "userCode", value = "用户code(移动端)", dataType = "file"),
            @ApiImplicitParam(name = "assessmentItemListStr", value = "扣分项list json字符串", required = true, dataType = "String"),
            @ApiImplicitParam(value = "操作类型:0草稿,1提交", name = "operationType", required = true),

    })
    public MessageBean<?> saveOrCommit(String assessmentItemListStr, MultipartFile[] files,
                                       String userCode, @SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user,
                                       String approverCodeListStr, String assessmentStr, Integer operationType) {
        List<StaffBean> staffBeanList = (List<StaffBean>) util.staff(userCode, null).getData();
        if (null == user) {
            if (null != staffBeanList && staffBeanList.size() > 0)
                user = staffBeanList.get(0);
        }
        if (null==user){
            MessageBean<?> msg=new MessageBean<>();
            msg.setCode(BusinessCode.NOT_LONGIN.getCode());
            msg.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return msg;
        }
        return assessmentService.saveOrCommit(assessmentItemListStr, files, userCode, user, approverCodeListStr, assessmentStr, operationType);
    }

    @ApiOperation("评估考核修改")
    @RequestMapping(value = "/update.htm", method = {RequestMethod.POST})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "approverCodeListStr", value = "审批人集合", dataType = "String"),
            @ApiImplicitParam(name = "assessmentStr", value = "审核对象字符串", dataType = "String"),
            @ApiImplicitParam(name = "files", value = "文件", dataType = "file"),
            @ApiImplicitParam(name = "userCode", value = "用户code(移动端)", dataType = "file"),
            @ApiImplicitParam(name = "assessmentItemListStr", value = "扣分项list json字符串", required = true, dataType = "String"),
    })
    public MessageBean<?> update(String assessmentItemListStr, @RequestBody MultipartFile[] files,
                                 @SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user,
                                 String userCode, String approverCodeListStr, String assessmentStr) {
        List<StaffBean> staffBeanList = (List<StaffBean>) util.staff(userCode, null).getData();
        if (null == user) {
            if (null != staffBeanList && staffBeanList.size() > 0)
                user = staffBeanList.get(0);
        }
        if (null==user){
            MessageBean<?> msg=new MessageBean<>();
            msg.setCode(BusinessCode.NOT_LONGIN.getCode());
            msg.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return msg;
        }
        return assessmentService.updateAssessment(assessmentItemListStr, files, user, userCode, approverCodeListStr, assessmentStr);
    }

    @ApiOperation("导出评估考核列表")
    @RequestMapping(value = "/export.htm", method = {RequestMethod.GET})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "assessmentYear", value = "年份", dataType = "Integer"),
            @ApiImplicitParam(name = "assessmentTimeType", value = "考核时间类型0年,1季度,2月份", dataType = "Integer"),
            @ApiImplicitParam(name = "assessmentTimeValue", value = "考核时间值", dataType = "Integer"),
            @ApiImplicitParam(name = "corpCode", value = "公司Code", dataType = "String"),
            @ApiImplicitParam(name = "corpName", value = "公司名称", dataType = "String"),
            @ApiImplicitParam(name = "assessmentType", value = "评估考核类型：0.标准化自评，1.年度评价，2.日常考核", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "assessmentGrade", value = "评估考核级别：0.集团对公司，1.公司对场站", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "deptName", value = "部门名称", dataType = "String"),
    })
    public HttpEntity<?> export(Integer assessmentGrade, String deptName, Integer assessmentTimeType, Integer assessmentTimeValue, Integer assessmentYear,
                                String corpName, Integer assessmentType, String corpCode) {
        Map<String, Object> map = new HashMap<>();
        if (assessmentGrade == null) {
            return null;
        }
        List<Assessment> list = assessmentService.getExportList(assessmentGrade, deptName, assessmentTimeType, assessmentTimeValue, assessmentYear, corpName, assessmentType, corpCode);
        map.put("data", list);
        map.put("assessmentGrade", assessmentGrade);
        File targetFile = new File("static/excel/AssessmentExport.xlsx");
        try {
            InputStream in = getClass().getClassLoader().getResourceAsStream("static/excel/AssessmentExport.xlsx");
            FileUtils.copyInputStreamToFile(in, targetFile);
        } catch (Exception e) {
            return null;
        }
        return Excel.createFile("考核评估列表", targetFile, "Assessment.btl", map);
    }

    @ApiOperation("导入评估考核列表")
    @RequestMapping(value = "/importExcel.htm", method = {RequestMethod.POST})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "approverCodeListStr", value = "审批人集合", dataType = "String"),
            @ApiImplicitParam(name = "corpCode", value = "公司code", required = true, dataType = "String"),
            @ApiImplicitParam(name = "assessmentType", value = "评估考核类型：0.标准化自评，1.年度评价，2.日常考核", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "assessmentGrade", value = "评估考核级别：0.集团对公司，1.公司对场站", required = true, dataType = "Integer"),
    })
    public MessageBean<?> importExcel(MultipartFile file, @SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user
            , Integer assessmentGrade, Integer assessmentType, String corpCode, String approverCodeListStr) {
        if (null==user){
            MessageBean<?> msg=new MessageBean<>();
            msg.setCode(BusinessCode.NOT_LONGIN.getCode());
            msg.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return msg;
        }
        return assessmentService.importFromExcel(file, user, assessmentGrade, assessmentType, corpCode, approverCodeListStr);
    }

    @ApiOperation("下载评估考核导入模板")
    @RequestMapping(value = "/downloadTemplate.htm", method = {RequestMethod.GET})
    public HttpEntity<?> downloadTemplate() {
        Map<String, Object> map = new HashMap<>();
        File targetFile = new File("static/excel/AssessmentImport.xlsx");
        try {
            InputStream in = getClass().getClassLoader().getResourceAsStream("static/excel/AssessmentImport.xlsx");
            FileUtils.copyInputStreamToFile(in, targetFile);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return Excel.createFile("评估考核导入模板", targetFile, "default.btl", map);
    }


    @ApiOperation("删除")
    @RequestMapping(value = "/delete.htm", method = {RequestMethod.POST})
    public MessageBean<?> delete(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user
            , String assessmentId, String userCode, String approverCodeListStr) {
        List<StaffBean> staffBeanList = (List<StaffBean>) util.staff(userCode, null).getData();
        if (null == user) {
            if (null != staffBeanList && staffBeanList.size() > 0)
                user = staffBeanList.get(0);
        }
        if (null==user){
            MessageBean<?> msg=new MessageBean<>();
            msg.setCode(BusinessCode.NOT_LONGIN.getCode());
            msg.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return msg;
        }
        return assessmentService.delete(user, assessmentId, approverCodeListStr);
    }

    @ApiOperation("流程中的业务数据")
    @ApiImplicitParam(name = "ids", value = "流程关联的业务ids", required = true, paramType = "query", dataType = "String")
    @RequestMapping(value = "/getProcessData.htm", method = {RequestMethod.GET})
    public MessageBean<?> getProcessData(String ids) {
        return assessmentService.getProcessData(ids);
    }


}
